﻿using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Model.DocumentDB
{
    /// <summary>Represents a collection within a DB account.</summary>
    public class CollectionViewModel : DocumentClientViewModelBase
    {
        private readonly DocumentCollection _collection;

        /// <summary>Constructor.</summary>
        /// <param name="client">Client API of the account.</param>
        /// <param name="collection">Collection object.</param>
        internal CollectionViewModel(DocumentClient client, DocumentCollection collection)
            : base(client)
        {
            if (collection == null)
            {
                throw new ArgumentNullException("collection");
            }

            _collection = collection;
        }

        /// <summary>Returns a lazy-loading collection of collections of a given database.</summary>
        /// <param name="client">Client API of the account.</param>
        /// <param name="collectionsLink">Link to collections.</param>
        /// <returns>Collections.</returns>
        internal static LoadableCollection<CollectionViewModel> GetLazyCollections(
            DocumentClient client,
            string collectionsLink)
        {
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }
            if (string.IsNullOrWhiteSpace(collectionsLink))
            {
                throw new ArgumentNullException("collectionsLink");
            }

            return new LoadableCollection<CollectionViewModel>(async () =>
            {
                var collections = await client.ReadDocumentCollectionFeedAsync(collectionsLink);
                var models = from collection in collections
                             let model = new CollectionViewModel(client, collection)
                             orderby model.Name
                             select model;

                return models;
            });
        }

        /// <summary>Collection name.</summary>
        public string Name
        {
            get { return _collection.Id; }
        }

        /// <summary>Collection link.</summary>
        public string SelfLink
        {
            get { return _collection.SelfLink; }
        }
    }
}